package com.wkq.net.gson

import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import java.io.IOException

/**
 * @Author: wkq
 * @Time: 2025/3/27 14:41
 * @Desc: 处理Gson 中String 默认值NULL转为""的适配器
 */
class StringTypeAdapter : TypeAdapter<String?>() {
    @Throws(IOException::class)
    override fun write(out: JsonWriter, value: String?) {
        var value = value
        try {
            if (value == null) {
                value = ""
            }
            out.value(value.toString())
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @Throws(IOException::class)
    override fun read(`in`: JsonReader): String? {
        var value: String?
        try {
            if (`in`.peek() == JsonToken.NULL) {
                `in`.nextNull()
                value = ""
                return value
            }
            if (`in`.peek() == JsonToken.STRING) {
                val str = `in`.nextString()
                value = str ?: ""
            } else {
                value = `in`.nextString()
            }
        } catch (e: Exception) {
            value = ""
        }
        return value
    }
}
